<template>
<n-modal v-model:show="bShowDialog">
    <n-card
        style="width: 600px"
        title="正在创建模型APP"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true">
        <div v-show="step==1" style="width:100%;height:100%">
            <AppProperties ref="refAppProps"></AppProperties>
            <div class="row end" style="margin-top:40px">
                <n-space>
                    <n-button @click="bShowDialog=false">取消</n-button>
                    <n-button type="primary" @click="createApp" :disabled="bUnknowPart">创建APP</n-button>
                </n-space>
            </div>
        </div>

        <div v-show="step==2" style="width:100%;height:100%">
            <div>正在打包并上传到主机零件 ...</div>
            <div class="grow">{{msg}}</div>
            <div v-show="bShowFinishBtns" class="row end">
                <n-button type="primary" @click="bShowDialog=false" >完成</n-button>
            </div>
        </div>
    </n-card>
</n-modal>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus';
import { ref, reactive, Ref, onMounted } from 'vue';
import { bus } from '@beshell/events-ts/bus'
import { AppModel, mapHostPartIDToClass } from '../../model/AppModel';
import { conn } from '@beshell/conn-ts/Connection';
import AppProperties from './AppProperties.vue';

const msg = ref("")
const bShowDialog = ref(false)

let step = ref(1)
let newApp: AppModel

let bShowFinishBtns = ref(false)
let bUnknowPart = ref(true)

const refAppProps = ref(null) as unknown as Ref<typeof AppProperties>


function popup(){
    if(!conn.isConnected) {
        window.$message.error("未连接到主机零件")
        return
    }
    bUnknowPart.value = !mapHostPartIDToClass[conn.meta.PART_ID]
    if(bUnknowPart.value) {
        msg.value = "未知的主机零件"
        return
    }

    msg.value = ''

    step.value = 1
    
    newApp = new AppModel
    refAppProps.value?.setModel(newApp)

    bShowDialog.value = true
}


async function createApp(){
    step.value = 2
    msg.value = ''

    try{
        // 为新模型创建目录
        msg.value = "正在创建APP目录 ..."
        newApp.folderPath = await conn.console.call(`beconsoled.createAppFolder("${newApp.pkgmeta.name}","${newApp.pkgmeta.uuid}")`)
        if(!newApp.folderPath) {
            msg.value = "在主机零件上创建APP目录失败"
            return
        }

        let partClass = mapHostPartIDToClass[conn.meta.PART_ID]
        newApp.addPart(partClass.name)

        // 
        newApp.save(null, (_msg:string)=>msg.value=_msg)

    } catch(e) {
        msg.value = '新建APP遇到了错误'
        console.error(e)
        return
    }

    msg.value = '已经创建了一个新的APP'
    bShowFinishBtns.value = true

    bus.emit("app.new", newApp)

    // 启动 workspace
    bShowDialog.value = false
    bus.emit("workspace.load()",newApp)
}

defineExpose({popup})
</script>